<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>距离计算</title>
    <!-- 1、引入资源 -->
    <script type="text/javascript">
        window._AMapSecurityConfig = {
          securityJsCode:"ec8990c1cac6e2f42866a4f908a19989",
        }
      </script>
      <script type="text/javascript"
      src="https://webapi.amap.com/maps?v=2.0&key=1d8c4c24f36ffedf82812d42f9835ac9"></script> 
    <!-- 3、形容容器 -->
    <style>
        body,html,#container{
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <!-- 2、创建容器 -->
    <div id="container"></div>
    <!-- 4、创建地图 -->
    <script>
        var map=new AMap.Map('container',{
            center:[116.39, 39.9],
            zoom:10,
        })
        // 5、创建两个点设置可拖动
        
        var m1=new AMap.Marker({
            map:map,//将m1添加进map
            draggable:true,//设置该点可拖动
            position:new AMap.LngLat(116.368904,39.913423),
        })
        var m2=new AMap.Marker({
            map:map,//将m1添加进map
            draggable:true,//设置该点可拖动
            position:new AMap.LngLat(116.382122,39.901176),
        })
        map.setFitView()

        // 6、准备一根线
        var line=new AMap.Polyline({
            strokeColor:'#80d8ff',//描边的颜色
            isOutline:true,
            outerlineColoe:'white',
        })
        line.setMap(map)

        // 7、准备文本
        var text =new AMap.Text({
            text:'',
            style:{
                'background-color':'#29b6f6',
                'border-color':'#e1f5fe',
                'font-size':'16px'
            },
        })
        text.setMap(map)
        // 8、计算
        function compute()
        {
            var p1=m1.getPosition()
            var p2=m2.getPosition()

            // 将文本放在线段中间
            var textposition=p1.divideBy(2).add(p2.divideBy(2))

            var distance=Math.round(p1.distance(p2))
            
            
            var path=[p1,p2]
            line.setPath(path)
            text.setText('距离为：'+distance +'米')
            text.setPosition(textposition)
        }
        // compute()
        m1.on('dragging',compute)
        m2.on('dragging',compute)
        
    </script>
</body>
</html>